<template>
    <div class="cluster-container">
      <div class="cluster-header">
        <el-image style="width: 100px; height: 100px" :src="require('@/assets/header_images/clusterManage.png')"></el-image>
        <div class="title">
          集群管理
          <div class="title-content">对多集群信息进行统一管理和协调，为容器服务调度提供部署环境，以实现高可用性和资源优化</div>
        </div>
      </div>
      <div class="top-content">
        <div class="cluster-info">
          <div class="cluster-operate">
              <span class="keyword">关键词：</span>
              <el-input
                placeholder="请输入名称、描述"
                v-model="searchInput"
                style="width: 20%;"
                prefix-icon="el-icon-search"
                clearable
                @input="filterClusterList">
              </el-input>
              <!-- <el-button icon="el-icon-search" circle @click="filterClusterList"></el-button> -->
              <div class="right-menu">
                <el-button style="width: 100px;background:#304156;color: #fff;" type="primary" plain @click="refreshPage">刷新</el-button>
                <el-button style="width: 100px;background:#304156;color: #fff;" type="primary" plain @click="uploadDialogVisible = true">添加</el-button>
              </div>
              <el-button style="width: 100px;" v-if="isRowSelected" type="danger" @click="deleteSelectedRow">删除</el-button>
          </div>
          <div class="cluster-table">
            <el-table
              ref="multipleTable"
              :data="filteredTableDate.length > 0 ? filteredTableDate : tableData"
              tooltip-effect="dark"
              align="center"
              style="width: 100%"
              @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="70"></el-table-column>
              <el-table-column prop="clusterZhname" label="名称" width="150"></el-table-column>
              <el-table-column prop="clusterDescription" label="集群描述" align="center" width="350"></el-table-column>
              <el-table-column prop="clusterUrl"
                label="集群地址"
                width="250"
                align="center">
              </el-table-column>
              <el-table-column
                label="创建时间"
                width="220"
                align="center">
                <template slot-scope="scope">
                  {{ scope.row.updateTime }}
                </template>
              </el-table-column>
              <el-table-column
                label="详细"
                width="150"
                align="center">
                <template slot-scope="scope">
                  <el-button size="small" style="background:rgb(221 220 244);" @click="looklook(scope.row)" >查看</el-button>
                  <!-- <el-button size="small" @click="echartsDialogVisible = true">查看</el-button> -->
                </template>
              </el-table-column>
              <el-table-column label="操作" width="230">
                <template slot-scope="scope">
                    <el-dropdown>
                        <span class="el-dropdown-link">
                            更多<i class="el-icon-arrow-down el-icon--right"></i>
                        </span>
                        <el-dropdown-menu slot="dropdown">
                            <el-button style="border: none;display:block;" @click="editCluster(scope.row)">编辑</el-button>
                            <el-button style="border: none;color:#F56C6C;" @click="deleteCluster(scope.row)">删除</el-button>
                        </el-dropdown-menu>
                    </el-dropdown>
                </template>
            </el-table-column>


            </el-table>
          </div>
          <div style="margin-top: 20px; float: right;">
              <el-pagination
                background
                layout="total, prev, pager, next"
                :total="page.total"
                :page-size="page.pageSize"
                :page.sync="page"
                @current-change="changePage"
              />
            </div>
        </div>
      </div>
      <div class="add-cluster">
        <el-dialog
          title="添加集群"
          :visible.sync="uploadDialogVisible"
          width="30%"
          :before-close="beforeCloseUploadDialog"
          :close-on-press-escape="false"
          :close-on-click-modal="false"
        >
          <el-form ref="uploadForm" :model="uploadInfo" label-width="80px">
            <el-form-item label="集群名称" prop="clusterZhname" required>
              <el-input v-model="uploadInfo.clusterZhname" placeholder="请输入长度小于24的中文"></el-input>
            </el-form-item>
            <el-form-item label="集群地址" prop="clusterUrl" required>
              <el-input v-model="uploadInfo.clusterUrl" placeholder="请输入IP地址格式内容"></el-input>
            </el-form-item>
            <el-form-item label="集群描述" prop="clusterDescription">
              <el-input v-model="uploadInfo.clusterDescription" placeholder="请输入长度小于128的中文"></el-input>
            </el-form-item>
            <el-form-item label="配置文件" prop="file" required>
              <el-upload
                class="uploadDiv"
                :action="uploadPath"
                :before-upload="beforeUpload"
                :limit="1"
                :file-list="fileList"
                :on-error="onUploadError"
                :disabled="fileList.length === 1"
                :destroy-on-close="true"
              >
                <el-button class="upload-button" size="small" type="primary" style="float: left;">点击上传</el-button>
              </el-upload>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="addCluster" style="float: right;">确定</el-button>
              <el-button type="primary" @click="closeUploadDialog" style="float: right;">取消</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>
      <div class="update-cluster">
        <el-dialog
          title="修改集群信息"
          :visible.sync="updateDialogVisible"
          width="30%"
          :before-close="beforeCloseUpdateDialog"
          :close-on-press-escape="false"
          :close-on-click-modal="false"
        >
          <el-form ref="updateForm" :model="uploadInfo" label-width="80px">
            <el-form-item label="集群名称" prop="clusterZhname">
              <el-input v-model="updateInfo.clusterZhname" placeholder="请输入长度小于24的中文"></el-input>
            </el-form-item>
            <el-form-item label="集群地址" prop="clusterUrl">
              <el-input v-model="updateInfo.clusterUrl" placeholder="请输入IP地址格式内容"></el-input>
            </el-form-item>
            <el-form-item label="集群描述" prop="clusterDescription">
              <el-input v-model="updateInfo.clusterDescription" placeholder="请输入长度小于128的中文"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="updateCluster">确定修改</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>
      <div>
        <el-dialog
          title="集群信息"
          :visible.sync="echartsDialogVisible"
          width="80%"
          :before-close="beforeCloseUploadDialog"
          :close-on-press-escape="false"
          :close-on-click-modal="false"
        >
          <div class="cluster-detail">
            <span style="width: 20%; text-align: center;margin-right: 10%;">集群名称: {{ this.lookInfo.clusterZhname }}</span>
            <span style="text-align: center;">|</span>
            <span style="width: 25%; text-align: center;">Kubernetes版本: {{ this.lookInfo.version }}</span>
            <span style="text-align: center;">|</span>
            <span style="width: 25%; margin-left: 2%; text-align: center;">创建时间: {{ this.lookInfo.updateTime }}</span>
          </div>
          <div style="display: flex;">
            <div ref="cpuChart" style="width: 100%; height: 400px;"></div>
            <div ref="memoryChart" style="width: 100%; height: 400px;" ></div>
            <div ref="podChart" style="width: 100%; height: 400px;"></div> 
          </div>
        </el-dialog>
      </div>
    </div>
  </template>
  
  <script>
  import * as echarts from 'echarts'

  export default {
    name: 'ClusterManage',
    data() {
      return{
        searchInput:'',
        uploadDialogVisible: false,
        updateDialogVisible:false,
        echartsDialogVisible: false,
        chart: null, 
        fileList: [],
        isRowSelected: false,
        tableData:[],
        mulipleSelection: [],
        filteredTableDate: [], //搜索结果
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        tmpPage: {
          filterKey: '',
          pageNum: 1,
          pageSize: 10
        },
        filterPage: {
          filterKey: 'aaa',
          pageNum: 1,
          pageSize: 10
        },
        detail: {
          id: ''
        },
        uploadInfo: {
          clusterZhname: '',
          clusterUrl: '',
          clusterDescription: '',
          file: null,
        },
        updateInfo:{
          clusterZhname: '',
          clusterUrl: '',
          clusterDescription: '',
          file: null,
        },
        lookInfo:{
          clusterZhname:'',
          version:'',
          updateTime:'',
        },
        echartsInfo:{
          cpuTotal: 0,
          cpuUsed: 0,
          memoryTotal: 0,
          memoryUsed: 0,
          podTotal: 0,
          podUsed: 0
        },
        topic: "",
        nameInput: '',
        addressInput: '',
        descriptionInput: '',
        baseUploadPath: "/gv-kube/resource/cluster/upload",
        uploadPath: "/gv-kube/resource/cluster/upload",
        // 校验
        namePattern: /^[\u4E00-\u9FA5]{1,24}$/, // 中文名称，长度小于24
        addressPattern: /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/, // IP地址格式
        descriptionPattern: /^.{0,128}$/,  // 中文描述  长度小于128
        file:''
      }
    },
    methods: {
      handleEchartsDialogVisibleChange(visible) {
        if (visible) {
          this.$nextTick(() => {
            this.initChart();
          });
        }
      },
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
        this.isRowSelected = val.length > 0; 
      },
      editCluster(row) {
        // 寻找原始数据的索引
        this.updateDialogVisible = true; // 打开编辑弹窗 

        const clusterZhname = row.clusterZhname;
        const clusterUrl = row.clusterUrl;
        const clusterDescription = row.clusterDescription;
        // 更新 updateInfo 对象的属性值
        this.updateInfo = {
          id:this.detail.id,
          clusterZhname: clusterZhname,
          clusterUrl: clusterUrl,
          clusterDescription: clusterDescription
        };
      },
      // 确定修改
      updateCluster(){
        console.log(this.updateInfo);
        this.$clusterManageApi.updateClusterInfo(this.updateInfo).then(res => {
          console.log("update",res);
          // 清空输入框
          this.nameInput = '';   
          this.addressInput = '';   
          this.descriptionInput = ''; 
          // 编辑保存成功后刷新页面
          this.getAllClusterByPage();
          this.closeUploadDialog();
        })
      },

      initChart() {      
        // 创建ECharts实例  
        const cpuChart = echarts.init(this.$refs.cpuChart);  
        const memoryChart = echarts.init(this.$refs.memoryChart);  
        const podChart = echarts.init(this.$refs.podChart);  
        // 计算已使用量占总量的百分比
        const cpuUsagePercentage = ((this.echartsInfo.cpuUsed / this.echartsInfo.cpuTotal) * 100).toFixed(0);
        const memoryUsagePercentage = ((this.echartsInfo.memoryUsed / this.echartsInfo.memoryTotal)* 100).toFixed(0);
        const podUsagePercentage = ((this.echartsInfo.podUsed / this.echartsInfo.podTotal) * 100).toFixed(0);

        // 设置ECharts配置项  
        const cpuOption = {  
            series: [  
                {   
                  name:'CPU',
                  type: 'gauge',  
                  radius: '90%',
                  progress: {
                    show: true
                  }, 
                  detail: {
                    valueAnimation: true,
                    formatter: `${cpuUsagePercentage}%\n\n\n\n\n\n\n已使用${this.echartsInfo.cpuTotal}核中的${this.echartsInfo.cpuUsed}`,
                    // offsetCenter: [0, '80%'],
                      textStyle: {
                        fontSize: 25
                      }
                  },
                  axisLabel: {
                    formatter: '{value}%'
                  },
                  data: [  
                    { value: cpuUsagePercentage, name:'CPU使用情况' }
                  ],  
                },  
            ],  
        };  

        const memoryOption = {  
            series: [  
                {  
                    type: 'gauge', 
                    radius: '90%',
                    progress: {
                      show: true
                    }, 
                    detail: {
                      valueAnimation: true,
                      formatter: `${memoryUsagePercentage}%\n\n\n\n\n\n\n已使用${this.echartsInfo.memoryTotal}G中的${this.echartsInfo.memoryUsed}`,
                      // formatter: `${memoryUsagePercentage}%`,
                      // offsetCenter: [0, '80%'],
                      textStyle: {
                        fontSize: 25
                      }
                    },
                    axisLabel: {
                      formatter: '{value}%'
                    }, 
                    data: [  
                        { value: memoryUsagePercentage, name: '内存使用情况' }
                    ],  
                },  
            ],  
        };  

        const podOption = {  
            series: [  
                {  
                    type: 'gauge',
                    radius: '90%',  
                    progress: {
                      show: true
                    }, 
                    detail: {
                      valueAnimation: true,
                      formatter: `${podUsagePercentage}%\n\n\n\n\n\n\n已使用${this.echartsInfo.podTotal}中的${this.echartsInfo.podUsed}`,
                      // offsetCenter: [0, '80%'],
                      textStyle: {
                        fontSize: 25
                      }
                    },
                    axisLabel: {
                      formatter: '{value}%'
                    }, 
                    data: [  
                        { value: podUsagePercentage, name: 'Pod使用情况' }
                    ],  
                },  
            ],  
        };  

        // 使用配置项显示图表  
        cpuChart.setOption(cpuOption);  
        memoryChart.setOption(memoryOption);  
        podChart.setOption(podOption);  
      },    
      // 分页获取所有集群信息
      getAllClusterByPage() {
        this.$clusterManageApi.pageGetCluster(this.tmpPage).then(res => {
          if (res && res.code === 200) {
            this.tableData = res.data.records
            this.page.total = res.data.total
            this.page.pageSize = res.data.pageSize
            this.detail.id = res.data.records[0].id
          }
        })
        .catch(error => {
          console.error(error);
        });
      },
      // 搜索过滤展示
      filterClusterList() {
        this.tmpPage.filterKey = this.searchInput;
        this.tmpPage.pageNum = 1;
        this.tmpPage.pageSize = 10;
        this.$clusterManageApi.filterCluster(this.tmpPage).then(res =>{
          // console.log("111");
        }).catch(error => {
              this.$message.error("搜索失败：" + error.message);
              console.log(error.message);
          });
        this.getAllClusterByPage();
      },

      // 选中数据 - 删除
      deleteSelectedRow() {
        this.$confirm('此操作将永久删除该集群, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const selectedRowsIds = this.multipleSelection.map(row => row.id);
          this.$clusterManageApi.delectCluster(selectedRowsIds).then(res => {
              this.tableData = this.tableData.filter(row => !selectedRowsIds.includes(row.id));
              this.multipleSelection = [];
              this.$message.success('删除成功');
          })
          // 清空选中的行
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },
      // 点击删除 - 删除
      deleteCluster(row) {
        console.log(row);
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const selectedRowId = [String(row.id)]; // 创建字符串数组并将 row.id 添加到数组中
          this.$clusterManageApi.delectCluster(selectedRowId).then(res => {
              this.$message.success('删除成功');
              this.getAllClusterByPage();
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });

      },

      looklook(info){
        console.log("获取到对应行的id",info.id);
        this.lookInfo.clusterZhname = info.clusterZhname;
        // 版本

        // 时间
        this.lookInfo.updateTime = info.updateTime;
        this.$clusterManageApi.getClusterDetail(info.id).then(res => {
          this.lookInfo.version = res.data.version;
          this.echartsInfo.cpuTotal = res.data.cpuTotal;
          this.echartsInfo.cpuUsed = res.data.cpuUsed;
          this.echartsInfo.memoryTotal = res.data.memoryTotal;
          this.echartsInfo.memoryUsed = res.data.memoryUsed;
          this.echartsInfo.podTotal = res.data.podTotal;
          this.echartsInfo.podUsed = res.data.podUsed;
          // console.log(re);
          // if (res && res.code === 200) {
            //   this.tableData = res.data.records
            //   this.page.total = res.data.total
            //   this.id = res.data.id
            // }
            this.echartsDialogVisible =  true;
            this.handleEchartsDialogVisibleChange(this.echartsDialogVisible)
          })
      },
      // 更换页数 
      changePage(currentPage) {
        this.page.currentPage = currentPage
        this.tmpPage.pageNum = currentPage
        this.getAllClusterByPage()
      },
      closeUploadDialog() {
        this.fileList = [];
        this.uploadDialogVisible = false;
        this.echartsDialogVisible = false;
        this.updateDialogVisible = false;
      },
      beforeUpload(file) {
        const isLt2G = file.size / 1024 / 1024 < 2048
        if (!isLt2G) {
          this.$message.error('上传文件大小不能超过 2048MB!')
        }else{
          this.fileList.push(file);
          console.log("this.fileList",this.fileList[0]);
        }
        return false
      },
      onUploadError(error) {
        this.$message.error("文件上传失败：" + error);
      },
      addCluster(){
         // 拿到上传时间，显示在table中
          let date = new Date()
          let year = date.getFullYear()
          let month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
          let day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
          let hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
          let minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
          let seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
          let time = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
          // 收集提交时的时间
          const newClusterInfo = {
            clusterZhname: this.uploadInfo.clusterZhname,
            clusterUrl: this.uploadInfo.clusterUrl,
            clusterDescription: this.uploadInfo.clusterDescription,
            updateTime: time // 将当前时间添加到新集群信息中
          };
          this.lookInfo.updateTime = time;
          console.log("this.lookInfo.updateTime",this.lookInfo.updateTime);
          // 检验输入内容是否匹配
            if (!this.namePattern.test(this.uploadInfo.clusterZhname)) {
                this.$message.error('请输入正确格式的集群名称（中文名称且长度小于24）');
                return;
            }
            if (!this.addressPattern.test(this.uploadInfo.clusterUrl)) {
                this.$message.error('请输入正确格式的集群地址（IP地址格式）');
                return;
            }
            if (!this.descriptionPattern.test(this.uploadInfo.clusterDescription)) {
                this.$message.error('请输入正确格式的集群描述（中文名称且长度小于128）');
                return;
            }
            console.log(newClusterInfo);
            // 推入新创建的对象
            // this.tableData.push(newClusterInfo);
          // 清空输入框
          this.nameInput = '';   
          this.addressInput = '';   
          this.descriptionInput = '';  

          // 关闭对话框
          this.uploadInfo.file = this.fileList[0];
          if(!this.uploadInfo.file){
            this.$message.error("请上传配置文件");
            return false;
          }else{
              this.closeUploadDialog(); 
              this.$refs.uploadForm.validate((valid) => {
                if (this.uploadInfo.file) {
                    this.$clusterManageApi.uploadAddCluster(this.uploadInfo)
                    .then(res => {
                      this.$message.success("添加成功");
                      this.getAllClusterByPage();
                      this.uploadDialogVisible = false;
                      // 清空数据
                      this.fileList = [];
                      this.uploadInfo = {
                        clusterZhname: '',
                        clusterUrl: '',
                        clusterDescription: '',
                        file: null,
                      };
                    })
                    .catch(error => {
                        this.$message.error("添加失败：" + error.message);
                    });
                    }else {
                  return false;
                }
            });
          }
           

      },
      refreshPage() {
          this.searchInput = '';
          this.getAllClusterByPage();
          this.$message.success('页面已刷新');
      },
      // beforeCloseUploadDialog(done) {
      //   this.$confirm('确认关闭？')
      //     .then(_ => {
      //       this.fileList = [];
      //       done()
      //     })
      //     .catch(_ => {
      //     })
      // },
      beforeCloseUploadDialog(done) {
        this.fileList = [];
        done()
      },
      beforeCloseUpdateDialog(done){
        this.fileList = [];
        done()
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`)
      },
    },
    mounted() {
      this.getAllClusterByPage();
    },
}
</script>

<style scoped>
.cluster-container {
  /* background-image: url(../../assets/back_images/background.png);  */
  background: #eff4f9;;
  background-size: cover;
  /* width: 98%; */
  /* margin-left: 1%; */
  padding: 20px;
  height: 92vh;
  display: flex;
  flex-direction: column;
  margin-bottom: 10px;
}

.cluster-header {
  width: 100%;
  height: 100px;
  margin-top: 6px;
  background-color: #fff;
  border-radius: 20px;
}

.title {
  display: inline-block;
  vertical-align: top;
  font-weight: 600;
  font-size: xx-large;
  padding: 20px;
}

.title-content {
  color: #888888;
  padding-top: 10px;
  font-size:small;
}

.cluster-detail{
  display: flex;
  justify-content: center;
  background-color: #d3e3fd;
  border: 1px solid #b8b4db;
  width: 90%;
  line-height: 30px;
  margin-left: 4%;
  margin-bottom: 10px;
}

.cluster-operate{
  background-color: #f9fbfd;
  /* border-radius:20px; */
  padding: 10px 0;
}
.keyword{
  color: #7d7575;
  font-weight: bold; 
  margin-right: 5px; 
  padding-left: 10px;
}

.cluster-info {
  margin-top: 10px;
  background-color: transparent;
}

.right-menu{
    display: inline;
    float: right;
    margin-right: 10px;
  }

  .delete-button {
    transition: opacity 0.5s ease; /* 使用 opacity 进行过渡，持续时间为 0.5 秒，缓动函数为 ease */
    opacity: 0; /* 初始状态为隐藏 */
  }

  .delete-button-show {
    opacity: 1; /* 显示状态 */
  }

  .cluster-table{
    /* width: 100%; */
    /* margin: 10px; */
    border: radius 40x;
    /* box-shadow: 1px 1px 9px #888888; */
  }

  .el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
  }

  .upload{
    display: flex;
    flex-direction: row;
    align-items: center;
  }
  .uploadDiv{
    padding-left: 14px;
  }
  .el-icon-arrow-down {
    font-size: 12px;
  }


::v-deep .el-input{
  width: 50%;
  margin-top: 4px;
  color: #7d7575;
}

::v-deep .el-table thead{
  font-size: initial;
  color: #606266;
  font-weight: 500;
}

::v-deep .el-image{
  margin-left: 20px;
}

::v-deep .el-input--suffix{
  width: 90%;
  margin-bottom: 5px;
  color: #7d7575;
}

::v-deep .el-button{
  border-radius: 30px;
  display: inline-block;
  margin: 0 8px;
}

::v-deep .el-dialog__title {
    line-height: 24px;
    font-size: 28px;
    color: #303133;
}

::v-deep .el-upload{
  display: block;
}

::v-deep .el-pagination__total{
  color: #7d7575;
}

</style>
  